package com.sskj.xyft.login;


import android.content.Context;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.sskj.xyft.MVPActivity;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.EditUtil;
import com.sskj.base.utils.SPUtils;
import com.sskj.base.view.ToolBarLayout;
import com.sskj.xyft.MyApplication;
import com.sskj.xyft.R;
import com.sskj.xyft.api.Api;
import com.sskj.xyft.login.data.LoginBean;
import com.sskj.xyft.main.MainActivity;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/03/21
 */
public class LoginActivity extends MVPActivity<LoginPresenter> {

    @BindView(R.id.login_account)
    EditText loginAccount;
    @BindView(R.id.login_ps)
    EditText loginPs;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.forget_ps)
    TextView forgetPs;
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.ps_lock)
    ImageView psLock;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public LoginPresenter getPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void initView() {
        toolbar.setLeftButtonOnClickListener(v -> finish());
        ClickUtil.click(toolbar.getRightButton(), view -> RegisterActivity.start(this));
        ClickUtil.click(forgetPs, view -> ForgetPasswordActivity.start(this));
        ClickUtil.click(loginBtn, view -> {
            if (isEmpty(loginAccount)) {
                ToastUtils.show(R.string.input_account);
                return;
            }
            if (isEmpty(loginPs)) {
                ToastUtils.show(R.string.input_login_ps);
                return;
            }
            mPresenter.login(getText(loginAccount), getText(loginPs));
        });
    }

    @Override
    public void initData() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        psLock.setOnClickListener(v -> {
            if (EditUtil.togglePs(loginPs)) {
                psLock.setImageResource(R.mipmap.icon_lock);
            } else {
                psLock.setImageResource(R.mipmap.icon_unlock);
            }
        });
    }

    public void loginSuccess(LoginBean data) {
        SPUtils.put(this, "token", data.getToken());
        SPUtils.put(this, "account", data.getAccount());
        MyApplication.token = data.getToken();
        MyApplication.account = data.getAccount();
        Intent intent = new Intent(this, MainActivity.class);
        if (Api.getInstance() != null) {
            Api.setInstance();
        }
        startActivity(intent);
        finish();
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

}
